package controller;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

import view.EmailView;
import view.SearchView;
import view.ViewHelpers;
import model.AppModel;
import model.Email;

/**
 * Initializes and controls the search view
 * 
 * This controller has a reference to the main model, and the current view it is working on.
 * It assigns handlers to events for the clear, search buttons and double clicking an email in the list.
 * It then specifies the actions to invoke upon triggering these events. 
 * 
 * @author MUSAB
 *
 * @version $Revision: 1.0 $
 */
public class SearchController {
	
	/**
	 * Application model
	 */
	private AppModel model;
	
	/**
	 * Search view
	 */
	private SearchView view;
	
	/**
	 * Constructor
	 * @param model AppModel
	 */
	public SearchController( AppModel model){
		
		this.model = model;
		view = new SearchView();
		assignHandlers();
		ViewHelpers.showDialog(view, "Search emails");
		
	}

	/**
	 * Assigns event handlers
	 */
	private void assignHandlers() {
		
		// Open email on double clicking
		view.getEmailsTable().addMouseListener(new MouseAdapter() {
		    public void mouseClicked(MouseEvent evt) {
		    	if (evt.getClickCount() == 2) {  
                    Point pnt = evt.getPoint();  
                    int row = view.getEmailsTable().rowAtPoint(pnt);  
                    previewEmail(row);
                }
		    }
		});
		
		// Clear click
		view.getClearBtn().addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				actionClear();
			}
		});
		
		// Search click
		view.getSearchBtn().addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				actionSearch();
			}
		});
	}

	/**
	 * Opens a the email in view mode
	 * 
	 * @param row
	 */
	protected void previewEmail(int row) {
		
		Integer id = Integer.valueOf( (String) view.getEmails().getValueAt(row, 0) );
		Email email = model.getUser().getEmail( id );
		
		if (email == null){
			ViewHelpers.alertError("The selected email no longer exists");
			return;
		}

		EmailView emailView = new EmailView();
		
		emailView.getTo().setText( email.getTo() );
		emailView.getFrom().setText( email.getFrom() );
		emailView.getDateTime().setText( email.getTimestamp().toString() );
		emailView.getSubject().setText(email.getSubject() );
		emailView.getBody().setText(email.getBody());
		
		ViewHelpers.showDialog(emailView, "Email preview");
	}

	/**
	 * Clears the search criteria fields
	 */
	protected void actionClear() {
		view.clearAll();
	}
	
	

	/**
	 * Performs the search and displays the result
	 */
	protected void actionSearch() {
		
		// If all fields were empty
		if (view.allFieldsEmpty()){
			ViewHelpers.alertError("No search criteria provided");
			return;
		}
		
		String to = view.getTo().getText();
		String from = view.getFrom().getText();
		String subject = view.getSubject().getText();
		String body = view.getBody().getText();
		
		// Perform the search
		List<Email> matchedEmails = model.getUser().searchEmails(to,from,subject,body);
		
		// Add to the view
		view.clearEmails();
		view.setMatches(matchedEmails.size());
		Integer count = 1;
		
		for(Email email : matchedEmails){
			view.getEmails().addRow(new String[]{
				String.valueOf(email.getId()),
				count.toString(),
				email.getTo(),
				email.getFrom(),
				email.getTimestamp().toString(),
				email.getSubject(),
				model.getUser().getFolder( email.getFolderId() ).getName()
			});
		}
	}

}
